// 交易管理
import accounting from 'accounting';
import classNames from 'classnames';
import { connect, routerRedux } from 'dva';
import moment from 'moment';
import React, { PureComponent } from 'react';

import myStyle from './index.less';

import url from '../../../assets/busi/userView/card_border_left.png';
import { TableC } from '../../../comps';
import CardC from '../../workStation/Barra/comps/cardC';

@connect(({ loading, tradeManageM }) => ({ loading, tradeManageM }))
export default class TradeManage extends PureComponent {
  // eslint-disable-next-line react/state-in-constructor
  state = {
    dataSource: [], // 表格数据
    totalData: {}, // 统计数据
    headerData: {}, // 统计数据第一排
    pageSize: 10,
    currentPage: 1,
  };

  getAllProduct = () => {
    this.props.dispatch({
      type: 'productManageM/getList',
      payload: {
        currentPage: 1,
        numInPage: 9999,
      },
      callback: (res) => {
        if (res) {
          this.setState({
            allProduct: res.dataSource,
          });
        }
      },
    });
  };

  componentDidMount() {
    this.getAllProduct();
    const { dispatch } = this.props;
    dispatch({
      type: 'tradeManageM/getTotalData',
      payload: {},
      callback: (totalData) => {
        if (totalData) {
          this.setState({ totalData });
        } else {
          this.setState({ totalData: {} });
        }
      },
    });
    dispatch({
      type: 'tradeManageM/getTableData',
      payload: {},
      callback: (dataSource, headerData) => {
        if (dataSource && headerData) {
          this.setState({ dataSource, headerData });
        } else {
          this.setState({ dataSource: [], headerData: {} });
        }
      },
    });
  }

  // 统计信息点击响应
  onclick = (type) => {
    // type:0-指令,1-簿记
    if (type == 0) {
      const tradeInstructionQuery = {
        search_GTE_createdTs: moment().format('YYYY-MM-DD'), // 开始时间
        search_LTE_createdTs: moment().format('YYYY-MM-DD'), // 结束时间
        search_EQ_busStatus: '6', // 指令状态
      };
      // 将条件缓存
      sessionStorage.setItem('tradeInstructionQuery', JSON.stringify(tradeInstructionQuery));
      // 转至【指令下达】-【指令查询】，默认带出查询条件中日期区间为当日、指令状态为已成交的查询结果，按成交时间倒序排序。
      this.props.dispatch(routerRedux.push(`/tradeInstruction/tradeInstructionQuery`));
    } else {
      const bookkeepingManagement = {
        search_GTE_createdTs: moment().format('YYYY-MM-DD'), // 开始时间
        search_LTE_createdTs: moment().format('YYYY-MM-DD'), // 结束时间
      };
      // 将条件缓存
      sessionStorage.setItem('bookkeepingManagement', JSON.stringify(bookkeepingManagement));
      this.props.dispatch(routerRedux.push(`/transactions/bookkeepingManagement`));
    }
  };

  handleTableChange = (pagination) => {
    const { current, pageSize } = pagination;
    this.setState({
      currentPage: current,
      pageSize,
    });
  };

  /** *
   *
   * @param e
   * @param record
   */
  pushRouter = (e, record) => {
    e.preventDefault();
    const { modes } = this.state.allProduct.find((v) => v.code === record.productCode);
    sessionStorage.setItem('tradeManageRecord', JSON.stringify({ ...record, modes }));
    this.props.dispatch(routerRedux.push('/performanceAnalysis/tradeAnalysisNew'));
  };

  changeColumn = (columns) => {
    columns.map((v) => {
      if (v.key === 'productName') {
        v.render = (val, record) => {
          if (val) {
            return (
              // eslint-disable-next-line jsx-a11y/anchor-is-valid,jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions
              <a
                onClick={(e) => {
                  this.pushRouter(e, record);
                }}
              >
                {`${record.productCode}-${val}`}
              </a>
            );
          }
          return '--';
        };
      }
    });
  };

  render() {
    const {
      tradeManageM: { columns },
    } = this.props;
    const { dataSource, totalData, currentPage, pageSize, headerData } = this.state;

    this.changeColumn(columns);

    const filterArr = [null, undefined];

    const isShowBoxTwo = () => {
      if (
        filterArr.includes(totalData.instructionNumber) &&
        filterArr.includes(totalData.instructionAmount) &&
        filterArr.includes(totalData.bookingNumber) &&
        filterArr.includes(totalData.bookingAmount)
      ) {
        return false;
      }
      return true;
    };
    return (
      <div>
        <CardC
          title='交易管理'
          type='22'
          noVideo={true}
          titleIsShow={false}
          content={
            <div>
              <div className={myStyle.box}>
                <div className={myStyle.boxOne}>
                  {/* eslint-disable-next-line jsx-a11y/alt-text */}
                  <img src={url} />
                  <div className={myStyle.showLeft}>
                    <span className={myStyle.title}>交易笔数：</span>
                    <span className={classNames(myStyle.number, myStyle.reWrite)}>
                      {headerData.transactionsNumber || headerData.transactionsNumber === 0 ? accounting.formatNumber(Number(headerData.transactionsNumber), 0) : '--'}
                    </span>
                  </div>
                  <div className={myStyle.showRight}>
                    <span className={myStyle.title}>交易金额：</span>
                    <span className={classNames(myStyle.number, myStyle.reWrite)}>
                      {headerData.transactionsAmount || headerData.transactionsAmount === 0
                        ? `${accounting.formatNumber(Number(headerData.transactionsAmount) / 10000, 2)}万`
                        : '0.00'}
                    </span>
                  </div>
                </div>
                {isShowBoxTwo() ? (
                  <div className={myStyle.boxTwo}>
                    <div className={myStyle.instructionBox}>
                      <div className={myStyle.showLeft}>
                        <span className={myStyle.title}>指令笔数：</span>
                        {/* eslint-disable-next-line jsx-a11y/anchor-is-valid,jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions */}
                        {totalData.instructionNumber ? <a onClick={() => this.onclick(0)}>{accounting.formatNumber(Number(totalData.instructionNumber), 0)}</a> : '--'}
                      </div>
                      <div className={myStyle.showRight}>
                        <span className={myStyle.title}>指令金额：</span>
                        {totalData.instructionAmount ? (
                          // eslint-disable-next-line jsx-a11y/anchor-is-valid,jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions
                          <a onClick={() => this.onclick(0)}>{`${accounting.formatNumber(Number(totalData.instructionAmount) / 10000, 2)}万`}</a>
                        ) : (
                          '--'
                        )}
                      </div>
                    </div>
                    <div className={myStyle.bookingBox}>
                      <div className={myStyle.showLeft}>
                        <span className={myStyle.title}>簿记笔数：</span>
                        {/* eslint-disable-next-line jsx-a11y/anchor-is-valid,jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions */}
                        {totalData.bookingNumber ? <a onClick={() => this.onclick(1)}>{accounting.formatNumber(Number(totalData.bookingNumber), 0)}</a> : '--'}
                      </div>
                      <div className={myStyle.showRight}>
                        <span className={myStyle.title}>簿记金额：</span>
                        {totalData.bookingAmount ? (
                          // eslint-disable-next-line jsx-a11y/anchor-is-valid,jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions
                          <a onClick={() => this.onclick(1)}>{totalData.bookingAmount ? `${accounting.formatNumber(Number(totalData.bookingAmount) / 10000, 2)}万` : '--'}</a>
                        ) : (
                          '--'
                        )}
                      </div>
                    </div>
                  </div>
                ) : (
                  <div className={myStyle.boxTwo} />
                )}
              </div>
              <TableC
                columns={columns}
                loading={this.props.loading.effects['tradeManageM/getTableData']}
                dataSource={dataSource}
                scroll={{ x: '600', y: '400' }}
                rowKey='productCode'
                current={currentPage}
                pageSize={pageSize}
                onChange={this.handleTableChange}
                size='small'
              />
            </div>
          }
        />
      </div>
    );
  }
}
